package com.asj.utils;

import static androidx.constraintlayout.widget.Constraints.TAG;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.Log;

import androidx.core.content.ContextCompat;

import com.asj.R;
import com.google.gson.JsonObject;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Objects;

/**
 * 七牛云文件上传工具
 * */
public class QiNiuYunUploader {
    private static final String ACCESS_KEY = "dCK8gYFUKomWKjL8soR4w9yFiQDUGNlS8FV9LeTZ";
    private static final String SECRET_KEY = "3CPFCISfhhd72Fcjkd0ivBGQVMyLHerQ_AxyRTi5";
    private static final String BUCKET_NAME = "aisheji-mdm";
    private static final String BASE_URL = "http://qny.aisheji.team";
    private static final String UPLOAD = "mdm/oppo/appIcon";
    private static final String defaultIconResName = "@mipmap/ic_launcher"; // 默认图标资源名称，例如 "@mipmap/ic_launcher"

    public static String saveIcon(Drawable appIcon,
                                  String appName,
                                  Context context,
                                  String packageName) throws IOException {

        if(appIcon == null){
            appIcon = ContextCompat.getDrawable(context, R.drawable.ic_launcher);
        }
        packageName = packageName.replace(".", "");
        // 指定文件路径和名称
        File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), appName+packageName+".png");
        //判断是否已经存在该文件
        String imagePathIfExists = getImagePathIfExists(UPLOAD + "/"+appName+packageName+".png");
        if(imagePathIfExists != null){
            System.out.println("文件已存在！" + imagePathIfExists);
            return BASE_URL+"/"+imagePathIfExists;
        }else{
            // 确保目录存在
            if (!Objects.requireNonNull(file.getParentFile()).exists()) {
                if (!file.getParentFile().mkdirs()) {
                    // 目录创建失败，处理错误
                    throw new IOException("目录创建失败！");
                }
            }
            FileOutputStream outputStream = null;
            try{
                outputStream = new FileOutputStream(file);
            }catch (Exception e){
                Log.e(TAG, "saveIcon: ", e);
            }

            Bitmap bitmap = null;
            // 确保Drawable是BitmapDrawable
            if (appIcon instanceof BitmapDrawable) {
                BitmapDrawable bitmapDrawable = (BitmapDrawable) appIcon;
                bitmap = bitmapDrawable.getBitmap();
            } else {
                // 获取 Drawable 的宽度和高度
                assert appIcon != null;
                int width = appIcon.getIntrinsicWidth();
                int height = appIcon.getIntrinsicHeight();

                // 配置 Bitmap
                bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                // 通过 Canvas 将 Drawable 绘制到 Bitmap 上
                Canvas canvas = new Canvas(bitmap);
                appIcon.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
                appIcon.draw(canvas);
            }
            assert outputStream != null;

            boolean isSaved = bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
            if (isSaved) {
                // 文件保存成功，调用自定义上传方法
                JsonObject result = QiNiuYunUploader.uploadFile(file);
                if(result == null){
                    throw new RuntimeException("上传文件出错，返回的内容为null");
                }
                //分类盒
                if(result.get("flag").getAsBoolean()){
                    return result.get("url").getAsString();
                }else{
                    throw new RuntimeException("存储应用图标失败！");
                }
            } else {
                // 文件保存失败，处理错误
                throw new RuntimeException("存储应用图标失败！");
            }
        }
    }


    public static JsonObject uploadFile(File file) throws QiniuException {
        try {
            //1、获取文件名
            String filename = UPLOAD + "/"+ file.getName();

            // 2. 构造一个带指定 Region 对象的配置类
            Configuration cfg = new Configuration(Region.huanan()); // 根据实际 Region 选择
            UploadManager uploadManager = new UploadManager(cfg);

            // 3. 获取七牛云提供的 token
            Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
            String upToken = auth.uploadToken(BUCKET_NAME);

            // 4. 定义上传文件的请求
            Response response = uploadManager.put(file, filename, upToken);
            int code = response.statusCode;

            // 5. 返回上传后的内容
            JsonObject jsonObject = new JsonObject();
            if (code == 200) {
                jsonObject.addProperty("flag", true);
                jsonObject.addProperty("url", BASE_URL + "/" + filename);
            } else {
                jsonObject.addProperty("flag", false);
                jsonObject.addProperty("url", "");
            }
            return jsonObject;
        } catch (IOException e) {
            Log.e("上传文件出错", Objects.requireNonNull(e.getMessage()));
        }
        return null;
    }

    /**
     * 判断云服务器上是否存在图标文件
     * */
    public static String getImagePathIfExists(String imageName) {
        Configuration cfg = new Configuration();
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        BucketManager bucketManager = new BucketManager(auth, cfg);

        try {
            // 检查图片是否存在
            bucketManager.stat(BUCKET_NAME, imageName);
            return imageName;
        } catch (QiniuException e ) {
            // 处理异常
            if (e.response.statusCode == 612) {
                System.out.println("文件不存在！需要进行上传：" + imageName);
            } else {
                Log.e("检查映像存在时出错", Objects.requireNonNull(e.getMessage()));
                System.err.println("检查映像存在时出错。");
            }
        }catch ( Exception exception){
            System.out.println("检测文件出现异常出现异常"+exception);
        }
        return null;
    }
}